<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        padding: 0px;
        margin: 0px;
        list-style: none;
      }
      main {
        width: 400px;
        margin: 20px auto;
        text-align: center;
      }
      .tp {
        width: 400px;
        height: 40px;
        border: 2px solid grey;
        border-radius: 1cap;
      }
      button {
        float: right;
      }
      li {
        height: 40px;
        line-height: 40px;
        font-size: 20px;
      }
      button {
        width: 40px;
        height: 40px;
      }
    </style>
  </head>
  <body>
    <main>
      <input class="tp" type="text" />
      <ul>
        <li>
          <span></span>
          <button>X</button>
        </li>
      </ul>
    </main>
  </body>
</html>
<script>
  let oul = document.querySelector("ul");
  let oipt = document.querySelector("input");
  const url = "http://localhost:3000/todos";
  function getTodo() {
    let xhr = new XMLHttpRequest();
    xhr.open("get", url);
    xhr.send();
    xhr.onload = function () {
      if (/^2/.test(xhr.status)) {
        let obj = JSON.parse(xhr.responseText);
        console.log(obj);
        oul.innerHTML = obj
          .map(
            (e) =>
              `<li>
                <input class='ck' type="checkbox">
                <span>${e.title}</span>
                <button data-id='${e.id}' class='dlt'>X</button>
            </li>`
          )
          .reverse()
          .join("");
      }
    };
  }
  getTodo();
  oipt.onkeydown = function (e) {
    if (e.keyCode == 13) {
      let title = oipt.value;
      let completed = false;
      let body = { title, completed };
      let xhr = new XMLHttpRequest();
      xhr.open("post", url);
      xhr.setRequestHeader("content-type", "application/json");
      xhr.send(JSON.stringify(body));
      xhr.onload = function () {
        if (/^2/.test(xhr.status)) {
          getTodo();
          oipt.value = "";
        }
      };
    }
  };
  oul.onclick = function (e) {
    if (e.target.className == "dlt") {
      let dltID = e.target.dataset.id;
      let xhr = new XMLHttpRequest();
      let dltAPI = url + "/" + dltID;
      xhr.open("DELETE", dltAPI);
      xhr.send();
      xhr.onload = function () {
        if (/^2/.test(xhr.status)) {
          getTodo();
        }
      };
    }
    if (e.target.className=='ck') {
        if (e.target.checked) {
            e.target.nextElementSibling.style.textDecoration='line-through'
        }else{
            e.target.nextElementSibling.style.textDecoration='none'
        }
    }
  };
</script>
